<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/Django框架/10-模型层-常用非常用字段和参数 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/Django框架/10-模型层-常用非常用字段和参数</h2>



  <p class="post-date">2020-09-24</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h2 id="1-ORM字段"><a href="#1-ORM字段" class="headerlink" title="1 ORM字段"></a>1 ORM字段</h2><h4 id="AutoField"><a href="#AutoField" class="headerlink" title="AutoField"></a>AutoField</h4><p>int自增列，必须填入参数 primary_key=True。当model中如果没有自增列，则自动会创建一个列名为id的列。</p>
<h4 id="IntegerField"><a href="#IntegerField" class="headerlink" title="IntegerField"></a>IntegerField</h4><p>一个整数类型,范围在 -2147483648 to 2147483647。</p>
<h4 id="CharField"><a href="#CharField" class="headerlink" title="CharField"></a>CharField</h4><p>字符类型，必须提供max_length参数， max_length表示字符长度。</p>
<h4 id="DateField"><a href="#DateField" class="headerlink" title="DateField"></a>DateField</h4><p>日期字段，日期格式 YYYY-MM-DD，相当于Python中的datetime.date()实例。</p>
<h4 id="DateTimeField"><a href="#DateTimeField" class="headerlink" title="DateTimeField"></a>DateTimeField</h4><p>日期时间字段，格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]，相当于Python中的datetime.datetime()实例</p>
<h3 id="常用和非常用字段"><a href="#常用和非常用字段" class="headerlink" title="常用和非常用字段"></a>常用和非常用字段</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br></pre></td><td class="code"><pre><span class="line">AutoField(Field)</span><br><span class="line">- int自增列，必须填入参数 primary_key=<span class="literal">True</span></span><br><span class="line"></span><br><span class="line">BigAutoField(AutoField)</span><br><span class="line">- bigint自增列，必须填入参数 primary_key=<span class="literal">True</span></span><br><span class="line"></span><br><span class="line">注：当model中如果没有自增列，则自动会创建一个列名为id的列</span><br><span class="line"><span class="keyword">from</span> django.db <span class="keyword">import</span> models</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserInfo</span><span class="params">(models.Model)</span>:</span></span><br><span class="line"><span class="comment"># 自动创建一个列名为id的且为自增的整数列</span></span><br><span class="line">username = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Group</span><span class="params">(models.Model)</span>:</span></span><br><span class="line"><span class="comment"># 自定义自增列</span></span><br><span class="line">nid = models.AutoField(primary_key=<span class="literal">True</span>)</span><br><span class="line">name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line"></span><br><span class="line">SmallIntegerField(IntegerField):</span><br><span class="line">- 小整数 <span class="number">-32768</span> ～ <span class="number">32767</span></span><br><span class="line"></span><br><span class="line">PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)</span><br><span class="line">- 正小整数 <span class="number">0</span> ～ <span class="number">32767</span></span><br><span class="line">IntegerField(Field)</span><br><span class="line">- 整数列(有符号的) <span class="number">-2147483648</span> ～ <span class="number">2147483647</span></span><br><span class="line"></span><br><span class="line">PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)</span><br><span class="line">- 正整数 <span class="number">0</span> ～ <span class="number">2147483647</span></span><br><span class="line"></span><br><span class="line">BigIntegerField(IntegerField):</span><br><span class="line">- 长整型(有符号的) <span class="number">-9223372036854775808</span> ～ <span class="number">9223372036854775807</span></span><br><span class="line"></span><br><span class="line">BooleanField(Field)</span><br><span class="line">- 布尔值类型</span><br><span class="line"></span><br><span class="line">NullBooleanField(Field):</span><br><span class="line">- 可以为空的布尔值</span><br><span class="line"></span><br><span class="line">CharField(Field)</span><br><span class="line">- 字符类型</span><br><span class="line">- 必须提供max_length参数， max_length表示字符长度</span><br><span class="line"></span><br><span class="line">TextField(Field)</span><br><span class="line">- 文本类型</span><br><span class="line"></span><br><span class="line">EmailField(CharField)：</span><br><span class="line">- 字符串类型，Django Admin以及ModelForm中提供验证机制</span><br><span class="line"></span><br><span class="line">IPAddressField(Field)</span><br><span class="line">- 字符串类型，Django Admin以及ModelForm中提供验证 IPV4 机制</span><br><span class="line"></span><br><span class="line">GenericIPAddressField(Field)</span><br><span class="line">- 字符串类型，Django Admin以及ModelForm中提供验证 Ipv4和Ipv6</span><br><span class="line">- 参数：</span><br><span class="line">protocol，用于指定Ipv4或Ipv6， <span class="string">'both'</span>,<span class="string">"ipv4"</span>,<span class="string">"ipv6"</span></span><br><span class="line">unpack_ipv4， 如果指定为<span class="literal">True</span>，则输入::ffff:<span class="number">192.0</span><span class="number">.2</span><span class="number">.1</span>时候，可解析为<span class="number">192.0</span><span class="number">.2</span><span class="number">.1</span>，开启此功能，需要protocol=<span class="string">"both"</span></span><br><span class="line"></span><br><span class="line">URLField(CharField)</span><br><span class="line">- 字符串类型，Django Admin以及ModelForm中提供验证 URL</span><br><span class="line"></span><br><span class="line">SlugField(CharField)</span><br><span class="line">- 字符串类型，Django Admin以及ModelForm中提供验证支持 字母、数字、下划线、连接符（减号）</span><br><span class="line"></span><br><span class="line">CommaSeparatedIntegerField(CharField)</span><br><span class="line">- 字符串类型，格式必须为逗号分割的数字</span><br><span class="line"></span><br><span class="line">UUIDField(Field)</span><br><span class="line">- 字符串类型，Django Admin以及ModelForm中提供对UUID格式的验证</span><br><span class="line"></span><br><span class="line">FilePathField(Field)</span><br><span class="line">- 字符串，Django Admin以及ModelForm中提供读取文件夹下文件的功能</span><br><span class="line">- 参数：</span><br><span class="line">path,                      文件夹路径</span><br><span class="line">match=<span class="literal">None</span>,                正则匹配</span><br><span class="line">recursive=<span class="literal">False</span>,           递归下面的文件夹</span><br><span class="line">allow_files=<span class="literal">True</span>,          允许文件</span><br><span class="line">allow_folders=<span class="literal">False</span>,       允许文件夹</span><br><span class="line"></span><br><span class="line">FileField(Field)</span><br><span class="line">- 字符串，路径保存在数据库，文件上传到指定目录</span><br><span class="line">- 参数：</span><br><span class="line">upload_to = <span class="string">""</span>      上传文件的保存路径</span><br><span class="line">storage = <span class="literal">None</span>      存储组件，默认django.core.files.storage.FileSystemStorage</span><br><span class="line"></span><br><span class="line">ImageField(FileField)</span><br><span class="line">- 字符串，路径保存在数据库，文件上传到指定目录</span><br><span class="line">- 参数：</span><br><span class="line">upload_to = <span class="string">""</span>      上传文件的保存路径</span><br><span class="line">storage = <span class="literal">None</span>      存储组件，默认django.core.files.storage.FileSystemStorage</span><br><span class="line">width_field=<span class="literal">None</span>,   上传图片的高度保存的数据库字段名（字符串）</span><br><span class="line">height_field=<span class="literal">None</span>   上传图片的宽度保存的数据库字段名（字符串）</span><br><span class="line"></span><br><span class="line">DateTimeField(DateField)</span><br><span class="line">- 日期+时间格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]</span><br><span class="line"></span><br><span class="line">DateField(DateTimeCheckMixin, Field)</span><br><span class="line">- 日期格式      YYYY-MM-DD</span><br><span class="line"></span><br><span class="line">TimeField(DateTimeCheckMixin, Field)</span><br><span class="line">- 时间格式      HH:MM[:ss[.uuuuuu]]</span><br><span class="line"></span><br><span class="line">DurationField(Field)</span><br><span class="line">- 长整数，时间间隔，数据库中按照bigint存储，ORM中获取的值为datetime.timedelta类型</span><br><span class="line"></span><br><span class="line">FloatField(Field)</span><br><span class="line">- 浮点型</span><br><span class="line"></span><br><span class="line">DecimalField(Field)</span><br><span class="line">- <span class="number">10</span>进制小数</span><br><span class="line">- 参数：</span><br><span class="line">max_digits，小数总长度</span><br><span class="line">decimal_places，小数位长度</span><br><span class="line"></span><br><span class="line">BinaryField(Field)</span><br><span class="line">- 二进制类型</span><br></pre></td></tr></table></figure>



<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">对应关系：</span><br><span class="line">    <span class="string">'AutoField'</span>: <span class="string">'integer AUTO_INCREMENT'</span>,</span><br><span class="line">    <span class="string">'BigAutoField'</span>: <span class="string">'bigint AUTO_INCREMENT'</span>,</span><br><span class="line">    <span class="string">'BinaryField'</span>: <span class="string">'longblob'</span>,</span><br><span class="line">    <span class="string">'BooleanField'</span>: <span class="string">'bool'</span>,</span><br><span class="line">    <span class="string">'CharField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line">    <span class="string">'CommaSeparatedIntegerField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line">    <span class="string">'DateField'</span>: <span class="string">'date'</span>,</span><br><span class="line">    <span class="string">'DateTimeField'</span>: <span class="string">'datetime'</span>,</span><br><span class="line">    <span class="string">'DecimalField'</span>: <span class="string">'numeric(%(max_digits)s, %(decimal_places)s)'</span>,</span><br><span class="line">    <span class="string">'DurationField'</span>: <span class="string">'bigint'</span>,</span><br><span class="line">    <span class="string">'FileField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line">    <span class="string">'FilePathField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line">    <span class="string">'FloatField'</span>: <span class="string">'double precision'</span>,</span><br><span class="line">    <span class="string">'IntegerField'</span>: <span class="string">'integer'</span>,</span><br><span class="line">    <span class="string">'BigIntegerField'</span>: <span class="string">'bigint'</span>,</span><br><span class="line">    <span class="string">'IPAddressField'</span>: <span class="string">'char(15)'</span>,</span><br><span class="line">    <span class="string">'GenericIPAddressField'</span>: <span class="string">'char(39)'</span>,</span><br><span class="line">    <span class="string">'NullBooleanField'</span>: <span class="string">'bool'</span>,</span><br><span class="line">    <span class="string">'OneToOneField'</span>: <span class="string">'integer'</span>,</span><br><span class="line">    <span class="string">'PositiveIntegerField'</span>: <span class="string">'integer UNSIGNED'</span>,</span><br><span class="line">    <span class="string">'PositiveSmallIntegerField'</span>: <span class="string">'smallint UNSIGNED'</span>,</span><br><span class="line">    <span class="string">'SlugField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line">    <span class="string">'SmallIntegerField'</span>: <span class="string">'smallint'</span>,</span><br><span class="line">    <span class="string">'TextField'</span>: <span class="string">'longtext'</span>,</span><br><span class="line">    <span class="string">'TimeField'</span>: <span class="string">'time'</span>,</span><br><span class="line">    <span class="string">'UUIDField'</span>: <span class="string">'char(32)'</span>,</span><br></pre></td></tr></table></figure>

<h2 id="2-ORM字段参数"><a href="#2-ORM字段参数" class="headerlink" title="2 ORM字段参数"></a>2 ORM字段参数</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#### null</span></span><br><span class="line"></span><br><span class="line">用于表示某个字段可以为空。</span><br><span class="line"></span><br><span class="line"><span class="comment">#### **unique**</span></span><br><span class="line"></span><br><span class="line">如果设置为unique=<span class="literal">True</span> 则该字段在此表中必须是唯一的 。</span><br><span class="line"></span><br><span class="line"><span class="comment">#### **db_index**</span></span><br><span class="line"></span><br><span class="line">如果db_index=<span class="literal">True</span> 则代表着为此字段设置索引。</span><br><span class="line"></span><br><span class="line"><span class="comment">#### **default**</span></span><br><span class="line"></span><br><span class="line">为该字段设置默认值。</span><br><span class="line"></span><br><span class="line"><span class="comment">###  DateField和DateTimeField</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#### auto_now_add</span></span><br><span class="line"></span><br><span class="line">配置auto_now_add=<span class="literal">True</span>，创建数据记录的时候会把当前时间添加到数据库。</span><br><span class="line"></span><br><span class="line"><span class="comment">#### auto_now</span></span><br><span class="line"></span><br><span class="line">配置上auto_now=<span class="literal">True</span>，每次更新数据记录的时候会更新该字段。</span><br></pre></td></tr></table></figure>







<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">null                数据库中字段是否可以为空</span><br><span class="line">db_column           数据库中字段的列名</span><br><span class="line">db_tablespace</span><br><span class="line">default             数据库中字段的默认值</span><br><span class="line">primary_key         数据库中字段是否为主键</span><br><span class="line">db_index            数据库中字段是否可以建立索引</span><br><span class="line">unique              数据库中字段是否可以建立唯一索引</span><br><span class="line">unique_for_date     数据库中字段【日期】部分是否可以建立唯一索引</span><br><span class="line">unique_for_month    数据库中字段【月】部分是否可以建立唯一索引</span><br><span class="line">unique_for_year     数据库中字段【年】部分是否可以建立唯一索引</span><br><span class="line"></span><br><span class="line">verbose_name        Admin中显示的字段名称</span><br><span class="line">blank               Admin中是否允许用户输入为空</span><br><span class="line">editable            Admin中是否可以编辑</span><br><span class="line">help_text           Admin中该字段的提示信息</span><br><span class="line">choices             Admin中显示选择框的内容，用不变动的数据放在内存中从而避免跨表操作</span><br><span class="line">如：gf = models.IntegerField(choices=[(<span class="number">0</span>, <span class="string">'何穗'</span>),(<span class="number">1</span>, <span class="string">'大表姐'</span>),],default=<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line">error_messages      自定义错误信息（字典类型），从而定制想要显示的错误信息；</span><br><span class="line">字典健：null, blank, invalid, invalid_choice, unique, <span class="keyword">and</span> unique_for_date</span><br><span class="line">如：&#123;<span class="string">'null'</span>: <span class="string">"不能为空."</span>, <span class="string">'invalid'</span>: <span class="string">'格式错误'</span>&#125;</span><br><span class="line"></span><br><span class="line">validators          自定义错误验证（列表类型），从而定制想要的验证规则</span><br><span class="line"><span class="keyword">from</span> django.core.validators <span class="keyword">import</span> RegexValidator</span><br><span class="line"><span class="keyword">from</span> django.core.validators <span class="keyword">import</span> EmailValidator,URLValidator,DecimalValidator,\</span><br><span class="line">MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator</span><br><span class="line">如：</span><br><span class="line">test = models.CharField(</span><br><span class="line">max_length=<span class="number">32</span>,</span><br><span class="line">error_messages=&#123;</span><br><span class="line"><span class="string">'c1'</span>: <span class="string">'优先错信息1'</span>,</span><br><span class="line"><span class="string">'c2'</span>: <span class="string">'优先错信息2'</span>,</span><br><span class="line"><span class="string">'c3'</span>: <span class="string">'优先错信息3'</span>,</span><br><span class="line">&#125;,</span><br><span class="line">validators=[</span><br><span class="line">RegexValidator(regex=<span class="string">'root_\d+'</span>, message=<span class="string">'错误了'</span>, code=<span class="string">'c1'</span>),</span><br><span class="line">RegexValidator(regex=<span class="string">'root_112233\d+'</span>, message=<span class="string">'又错误了'</span>, code=<span class="string">'c2'</span>),</span><br><span class="line">EmailValidator(message=<span class="string">'又错误了'</span>, code=<span class="string">'c3'</span>), ]</span><br><span class="line">                            )</span><br></pre></td></tr></table></figure>



<h2 id="3-关系字段"><a href="#3-关系字段" class="headerlink" title="3 关系字段"></a>3 关系字段</h2><h3 id="ForeignKey"><a href="#ForeignKey" class="headerlink" title="ForeignKey"></a>ForeignKey</h3><p>外键类型在ORM中用来表示外键关联关系，一般把ForeignKey字段设置在 ‘一对多’中’多’的一方。</p>
<p>ForeignKey可以和其他表做关联关系同时也可以和自身做关联关系。</p>
<h4 id="to"><a href="#to" class="headerlink" title="to"></a>to</h4><p>设置要关联的表</p>
<h4 id="to-field"><a href="#to-field" class="headerlink" title="to_field"></a>to_field</h4><p>设置要关联的表的字段</p>
<h4 id="related-name"><a href="#related-name" class="headerlink" title="related_name"></a>related_name</h4><p>反向操作时，使用的字段名，用于代替原反向查询时的’表名_set’。</p>
<p>例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Classes</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    theclass = models.ForeignKey(to=<span class="string">"Classes"</span>)</span><br></pre></td></tr></table></figure>

<p>当我们要查询某个班级关联的所有学生（反向查询）时，我们会这么写：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">models.Classes.objects.first().student_set.all()</span><br></pre></td></tr></table></figure>

<p>当我们在ForeignKey字段中添加了参数 related_name 后，</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    theclass = models.ForeignKey(to=<span class="string">"Classes"</span>, related_name=<span class="string">"students"</span>)</span><br></pre></td></tr></table></figure>

<p>当我们要查询某个班级关联的所有学生（反向查询）时，我们会这么写：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">models.Classes.objects.first().students.all()</span><br></pre></td></tr></table></figure>

<h4 id="related-query-name"><a href="#related-query-name" class="headerlink" title="related_query_name"></a><strong>related_query_name</strong></h4><p>反向查询操作时，使用的连接前缀，用于替换表名。</p>
<h4 id="on-delete"><a href="#on-delete" class="headerlink" title="on_delete"></a><strong>on_delete</strong></h4><p>　　当删除关联表中的数据时，当前表与其关联的行的行为。</p>
<p>　　<strong>models.CASCADE</strong><br>　　删除关联数据，与之关联也删除</p>
<p>　　<strong>models.DO_NOTHING</strong><br>　　删除关联数据，引发错误IntegrityError</p>
<p>　　<strong>models.PROTECT</strong><br>　　删除关联数据，引发错误ProtectedError</p>
<p>　　<strong>models.SET_NULL</strong><br>　　删除关联数据，与之关联的值设置为null（前提FK字段需要设置为可空）</p>
<p>　　<strong>models.SET_DEFAULT</strong><br>　　删除关联数据，与之关联的值设置为默认值（前提FK字段需要设置默认值）</p>
<p>　　<strong>models.SET</strong></p>
<p>　　删除关联数据，<br>　　a. 与之关联的值设置为指定值，设置：models.SET(值)<br>　　b. 与之关联的值设置为可执行对象的返回值，设置：models.SET(可执行对象)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">def func():</span><br><span class="line">    return 10</span><br><span class="line"></span><br><span class="line">class MyModel(models.Model):</span><br><span class="line">    user &#x3D; models.ForeignKey(</span><br><span class="line">        to&#x3D;&quot;User&quot;,</span><br><span class="line">        to_field&#x3D;&quot;id&quot;，</span><br><span class="line">        on_delete&#x3D;models.SET(func)</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>



<h4 id="db-constraint"><a href="#db-constraint" class="headerlink" title="db_constraint"></a>db_constraint</h4><p>是否在数据库中创建外键约束，默认为True。</p>
<h3 id="OneToOneField"><a href="#OneToOneField" class="headerlink" title="OneToOneField"></a>OneToOneField</h3><p>一对一字段。</p>
<p>通常一对一字段用来扩展已有字段。</p>
<p>一对一的关联关系多用在当一张表的不同字段查询频次差距过大的情况下，将本可以存储在一张表的字段拆开放置在两张表中，然后将两张表建立一对一的关联关系。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Author</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    info = models.OneToOneField(to=<span class="string">'AuthorInfo'</span>)</span><br><span class="line">    </span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AuthorInfo</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    phone = models.CharField(max_length=<span class="number">11</span>)</span><br><span class="line">    email = models.EmailField()</span><br></pre></td></tr></table></figure>

<h4 id="to-1"><a href="#to-1" class="headerlink" title="to"></a>to</h4><p>设置要关联的表。</p>
<h4 id="to-field-1"><a href="#to-field-1" class="headerlink" title="to_field"></a>to_field</h4><p>设置要关联的字段。</p>
<h4 id="on-delete-1"><a href="#on-delete-1" class="headerlink" title="on_delete"></a>on_delete</h4><p>同ForeignKey字段。</p>
<h3 id="ManyToManyField"><a href="#ManyToManyField" class="headerlink" title="ManyToManyField"></a>ManyToManyField</h3><p>用于表示多对多的关联关系。在数据库中通过第三张表来建立关联关系</p>
<h4 id="to-2"><a href="#to-2" class="headerlink" title="to"></a>to</h4><p>设置要关联的表</p>
<h4 id="related-name-1"><a href="#related-name-1" class="headerlink" title="related_name"></a>related_name</h4><p>同ForeignKey字段。</p>
<h4 id="related-query-name-1"><a href="#related-query-name-1" class="headerlink" title="related_query_name"></a>related_query_name</h4><p>同ForeignKey字段。</p>
<h4 id="symmetrical"><a href="#symmetrical" class="headerlink" title="symmetrical"></a>symmetrical</h4><p>仅用于多对多自关联时，指定内部是否创建反向操作的字段。默认为True。</p>
<p>举个例子：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">16</span>)</span><br><span class="line">    friends = models.ManyToManyField(<span class="string">"self"</span>)</span><br></pre></td></tr></table></figure>

<p>此时，person对象就没有person_set属性。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">16</span>)</span><br><span class="line">    friends = models.ManyToManyField(<span class="string">"self"</span>, symmetrical=<span class="literal">False</span>)</span><br></pre></td></tr></table></figure>

<p>此时，person对象现在就可以使用person_set属性进行反向查询。</p>
<h4 id="through"><a href="#through" class="headerlink" title="through"></a>through</h4><p>在使用ManyToManyField字段时，Django将自动生成一张表来管理多对多的关联关系。</p>
<p>但我们也可以手动创建第三张表来管理多对多关系，此时就需要通过through来指定第三张表的表名。</p>
<h4 id="through-fields"><a href="#through-fields" class="headerlink" title="through_fields"></a><strong>through_fields</strong></h4><p>设置关联的字段。</p>
<h4 id="db-table"><a href="#db-table" class="headerlink" title="db_table"></a>db_table</h4><p>默认创建第三张表时，数据库中表的名称。</p>
<h2 id="4-多对多关联关系的三种方式"><a href="#4-多对多关联关系的三种方式" class="headerlink" title="4 多对多关联关系的三种方式"></a>4 多对多关联关系的三种方式</h2><h3 id="方式一：自行创建第三张表"><a href="#方式一：自行创建第三张表" class="headerlink" title="方式一：自行创建第三张表"></a>方式一：自行创建第三张表</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Book</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    title = models.CharField(max_length=<span class="number">32</span>, verbose_name=<span class="string">"书名"</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Author</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">32</span>, verbose_name=<span class="string">"作者姓名"</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 自己创建第三张表，分别通过外键关联书和作者</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Author2Book</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    author = models.ForeignKey(to=<span class="string">"Author"</span>)</span><br><span class="line">    book = models.ForeignKey(to=<span class="string">"Book"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">        unique_together = (<span class="string">"author"</span>, <span class="string">"book"</span>)</span><br></pre></td></tr></table></figure>



<h3 id="方式二：通过ManyToManyField自动创建第三张表"><a href="#方式二：通过ManyToManyField自动创建第三张表" class="headerlink" title="方式二：通过ManyToManyField自动创建第三张表"></a>方式二：通过ManyToManyField自动创建第三张表</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Book</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    title = models.CharField(max_length=<span class="number">32</span>, verbose_name=<span class="string">"书名"</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 通过ORM自带的ManyToManyField自动创建第三张表</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Author</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">32</span>, verbose_name=<span class="string">"作者姓名"</span>)</span><br><span class="line">    books = models.ManyToManyField(to=<span class="string">"Book"</span>, related_name=<span class="string">"authors"</span>)</span><br></pre></td></tr></table></figure>

<h3 id="方式三：设置ManyTomanyField并指定自行创建的第三张表"><a href="#方式三：设置ManyTomanyField并指定自行创建的第三张表" class="headerlink" title="方式三：设置ManyTomanyField并指定自行创建的第三张表"></a>方式三：设置ManyTomanyField并指定自行创建的第三张表</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Book</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    title = models.CharField(max_length=<span class="number">32</span>, verbose_name=<span class="string">"书名"</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 自己创建第三张表，并通过ManyToManyField指定关联</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Author</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">32</span>, verbose_name=<span class="string">"作者姓名"</span>)</span><br><span class="line">    books = models.ManyToManyField(to=<span class="string">"Book"</span>, through=<span class="string">"Author2Book"</span>, through_fields=(<span class="string">"author"</span>, <span class="string">"book"</span>))</span><br><span class="line">    <span class="comment"># through_fields接受一个2元组（'field1'，'field2'）：</span></span><br><span class="line">    <span class="comment"># 其中field1是定义ManyToManyField的模型外键的名（author），field2是关联目标模型（book）的外键名。</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Author2Book</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    author = models.ForeignKey(to=<span class="string">"Author"</span>)</span><br><span class="line">    book = models.ForeignKey(to=<span class="string">"Book"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">        unique_together = (<span class="string">"author"</span>, <span class="string">"book"</span>)</span><br></pre></td></tr></table></figure>

<p>注意：</p>
<p>当我们需要在第三张关系表中存储额外的字段时，就要使用第三种方式。</p>
<p>但是当我们使用第三种方式创建多对多关联关系时，就无法使用set、add、remove、clear方法来管理多对多的关系了，需要通过第三张表的model来管理多对多关系。</p>
<h2 id="5-元信息"><a href="#5-元信息" class="headerlink" title="5 元信息"></a>5 元信息</h2><p>ORM对应的类里面包含另一个Meta类，而Meta类封装了一些数据库的信息。主要字段如下:</p>
<h4 id="db-table-1"><a href="#db-table-1" class="headerlink" title="db_table"></a><strong>db_table</strong></h4><p>ORM在数据库中的表名默认是 <strong>app_</strong>类名，可以通过<strong>db_table</strong>可以重写表名。</p>
<h4 id="index-together"><a href="#index-together" class="headerlink" title="index_together"></a>index_together</h4><p>联合索引。</p>
<h4 id="unique-together"><a href="#unique-together" class="headerlink" title="unique_together"></a>unique_together</h4><p>联合唯一索引。</p>
<h4 id="ordering"><a href="#ordering" class="headerlink" title="ordering"></a>ordering</h4><p>指定默认按什么字段排序。</p>
<p>只有设置了该属性，我们查询到的结果才可以被reverse()。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserInfo</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    nid = models.AutoField(primary_key=<span class="literal">True</span>)</span><br><span class="line">    username = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">        <span class="comment"># 数据库中生成的表名称 默认 app名称 + 下划线 + 类名</span></span><br><span class="line">        db_table = <span class="string">"table_name"</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 联合索引</span></span><br><span class="line">        index_together = [</span><br><span class="line">            (<span class="string">"pub_date"</span>, <span class="string">"deadline"</span>),</span><br><span class="line">        ]</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 联合唯一索引</span></span><br><span class="line">        unique_together = ((<span class="string">"driver"</span>, <span class="string">"restaurant"</span>),)</span><br><span class="line">        </span><br><span class="line">        ordering = (<span class="string">'name'</span>,)</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># admin中显示的表名称</span></span><br><span class="line">        verbose_name=<span class="string">'哈哈'</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># verbose_name加s</span></span><br><span class="line">        verbose_name_plural=verbose_name</span><br></pre></td></tr></table></figure>

<h2 id="6-自定义字段（了解）"><a href="#6-自定义字段（了解）" class="headerlink" title="6 自定义字段（了解）"></a>6 自定义字段（了解）</h2><p>自定义char类型字段：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FixedCharField</span><span class="params">(models.Field)</span>:</span></span><br><span class="line">    <span class="string">"""</span></span><br><span class="line"><span class="string">    自定义的char类型的字段类</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, max_length, *args, **kwargs)</span>:</span></span><br><span class="line">        self.max_length = max_length</span><br><span class="line">        super(FixedCharField, self).__init__(max_length=max_length, *args, **kwargs)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">db_type</span><span class="params">(self, connection)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">        限定生成数据库表的字段类型为char，长度为max_length指定的值</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">'char(%s)'</span> % self.max_length</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Class</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    id = models.AutoField(primary_key=<span class="literal">True</span>)</span><br><span class="line">    title = models.CharField(max_length=<span class="number">25</span>)</span><br><span class="line">    <span class="comment"># 使用自定义的char类型的字段</span></span><br><span class="line">    cname = FixedCharField(max_length=<span class="number">25</span>)</span><br></pre></td></tr></table></figure>

</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/python/Django%E6%A1%86%E6%9E%B6/2-Http%E5%8D%8F%E8%AE%AE/">
        <span class="nav-arrow">← </span>
        
          python/Django框架/2-Http协议
        
      </a>
    
    
      <a class="nav-right" href="/python/Django%E6%A1%86%E6%9E%B6/4-Django%E7%AE%80%E4%BB%8B/">
        
          python/Django框架/4-Django简介
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-ORM字段"><span class="toc-nav-text">1 ORM字段</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#AutoField"><span class="toc-nav-text">AutoField</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#IntegerField"><span class="toc-nav-text">IntegerField</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#CharField"><span class="toc-nav-text">CharField</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#DateField"><span class="toc-nav-text">DateField</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#DateTimeField"><span class="toc-nav-text">DateTimeField</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#常用和非常用字段"><span class="toc-nav-text">常用和非常用字段</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-ORM字段参数"><span class="toc-nav-text">2 ORM字段参数</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#3-关系字段"><span class="toc-nav-text">3 关系字段</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#ForeignKey"><span class="toc-nav-text">ForeignKey</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#to"><span class="toc-nav-text">to</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#to-field"><span class="toc-nav-text">to_field</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#related-name"><span class="toc-nav-text">related_name</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#related-query-name"><span class="toc-nav-text">related_query_name</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#on-delete"><span class="toc-nav-text">on_delete</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#db-constraint"><span class="toc-nav-text">db_constraint</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#OneToOneField"><span class="toc-nav-text">OneToOneField</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#to-1"><span class="toc-nav-text">to</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#to-field-1"><span class="toc-nav-text">to_field</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#on-delete-1"><span class="toc-nav-text">on_delete</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#ManyToManyField"><span class="toc-nav-text">ManyToManyField</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#to-2"><span class="toc-nav-text">to</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#related-name-1"><span class="toc-nav-text">related_name</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#related-query-name-1"><span class="toc-nav-text">related_query_name</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#symmetrical"><span class="toc-nav-text">symmetrical</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#through"><span class="toc-nav-text">through</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#through-fields"><span class="toc-nav-text">through_fields</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#db-table"><span class="toc-nav-text">db_table</span></a></li></ol></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-多对多关联关系的三种方式"><span class="toc-nav-text">4 多对多关联关系的三种方式</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#方式一：自行创建第三张表"><span class="toc-nav-text">方式一：自行创建第三张表</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#方式二：通过ManyToManyField自动创建第三张表"><span class="toc-nav-text">方式二：通过ManyToManyField自动创建第三张表</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#方式三：设置ManyTomanyField并指定自行创建的第三张表"><span class="toc-nav-text">方式三：设置ManyTomanyField并指定自行创建的第三张表</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#5-元信息"><span class="toc-nav-text">5 元信息</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#db-table-1"><span class="toc-nav-text">db_table</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#index-together"><span class="toc-nav-text">index_together</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#unique-together"><span class="toc-nav-text">unique_together</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#ordering"><span class="toc-nav-text">ordering</span></a></li></ol></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#6-自定义字段（了解）"><span class="toc-nav-text">6 自定义字段（了解）</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/Django框架/10-模型层-常用非常用字段和参数/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/Django框架/10-模型层-常用非常用字段和参数",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>